package indigo.mybatis.entity;

import java.util.Map;

import com.google.common.collect.Maps;

public class SimpleSqlEntityManager implements SqlEntityManager {
	private final EntityMetadataReader metadataReader;

	private final Map<Class<?>, EntityMetadata<?>> metadataTypeMap = Maps.newConcurrentMap();
	private final Map<String, EntityMetadata<?>> metadataNameMap = Maps.newConcurrentMap();

	public SimpleSqlEntityManager() {
		this(new AnnotationEntityMetadataReader());
	}

	public SimpleSqlEntityManager(EntityMetadataReader metadataReader) {
		this.metadataReader = metadataReader;
	}

	@Override
	public synchronized void addEntity(Class<?> type) {
		if (metadataTypeMap.containsKey(type)) {
			throw new IllegalStateException("Duplicated entity type: " + type.getName());
		}
		EntityMetadata<?> metadata = metadataReader.getEntityMetadata(type);
		metadataTypeMap.put(type, metadata);
		metadataNameMap.put(metadata.getName(), metadata);
	}

	@Override
	public Class<?>[] getEntityTypes() {
		return metadataTypeMap.keySet().toArray(new Class<?>[0]);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> EntityMetadata<T> getEntityMetadata(Class<T> type) {
		return (EntityMetadata<T>) metadataTypeMap.get(type);
	}

	@Override
	public EntityMetadata<?> getEntityMetadataByName(String name) {
		return metadataNameMap.get(name);
	}
}
